package com.ryskoo.basicdata.industry.repository;

import com.ryskoo.basicdata.industry.domain.IndustryPO;
import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author BeHappy
 */
@Primary
@Repository
public class IndustryRedisImpl extends BasicRedisImpl<IndustryPO> implements IIndustryRepository{
    @Autowired
    private RedisUtil redisClient;

    @Autowired
    private IIndustryRepository industryRepository;

    /**
     * 行业集合缓存KEY
     */
    private static final String cacheListKey = CacheConstant.BDS_INDUSTRY_LIST_KEY;

    /**
     * 行业缓存KEY
     */
    private static final String cacheKey = CacheConstant.BDS_INDUSTRY_KEY;

    @PostConstruct
    public void init() {
        this.setRedisClient(redisClient);
        this.setDao(industryRepository);
    }

    public IndustryRedisImpl() {
        super(cacheKey);
    }

    @Override
    public void create(IndustryPO industryPO) {
        super.create(industryPO);
        redisClient.remove(cacheListKey);
    }

    @Override
    public void update(IndustryPO industryPO) {
        super.update(industryPO);
        redisClient.remove(cacheListKey);
    }

    @Override
    public void delete(IndustryPO industryPO) {
        super.delete(industryPO);
        redisClient.remove(cacheListKey);
    }

    @Override
    public void deletes(List<String> needDeleteUuids) {
        super.deletes(needDeleteUuids);
        redisClient.remove(cacheListKey);
    }

    /**
     * 不带条件查询所有对象
     */
    @Override
    public List<IndustryPO> getAll() {
        //从缓存获取行业集合
        Object object = redisClient.getSession(cacheListKey);

        if (object != null) {
            List<IndustryPO> cacheList = (List<IndustryPO>)object;
            return cacheList;
        }

        //获取所有的行业，并放入缓存
        List<IndustryPO> list = super.getAll();

        if(list != null && list.size() > 0){
            for (IndustryPO po : list) {
                redisClient.setObject(cacheKey + po.getUuid(), po);
            }
        }

        //将结果放入缓存
        redisClient.setExpireSession(cacheListKey, list, null);

        return list;
    }

}
